<template>
    <div class="container">
        <!-- 导航栏区域开始 -->
        <TridentNavBar>
            <template #left><i class="iconfont icon-zuojiantou"></i></template>
            <template #default>群公告</template>
            <template #right v-if="isAdmin"><span @click="handleShowPublish" style="border: 1px solid #fff;padding: 5px 10px;">发布</span></template>
        </TridentNavBar>
        <!-- 导航栏区域结束 -->

        <!-- 列表区域开始 -->
        <div class="content-wrap">
            <van-pull-refresh
                v-model="refreshing"
                @refresh="onRefresh"
                style="min-height: calc(100vh - 60px);"
            >
                <van-list
                    v-model:loading="loading"
                    :finished="finished"
                    :finished-text="totalPage > 1 ? '没有更多了' : ''"
                    @load="getGroupNoticeList"
                    offset="50"
                    class="list-wrap"
                >

                    <!-- 骨架屏区域 -->
                    <div class="skeleton-item" v-for="(index) in 6" :key="index" v-if="isSkeleton">
                        <van-skeleton>
                            <template #template>
                                <div class="skeleton-box">
                                    <div class="title">
                                        <van-skeleton-paragraph row-width="20%" />
                                    </div>

                                    <div class="content">
                                        <van-skeleton-paragraph row-width="100%" />
                                        <van-skeleton-paragraph row-width="100%" style="margin: 5px 0;"/>
                                        <van-skeleton-paragraph row-width="100%" />
                                    </div>
                                    <div class="footer">
                                        <van-skeleton-paragraph row-width="36%" />
                                    </div>
                                </div>
                            </template>
                        </van-skeleton>
                    </div>

                    <template v-if="groupNoticeList.length > 0">
                        <div class="item" v-for="(item, index) in groupNoticeList" :key="index">
                            <!-- 头部区域开始 -->
                            <div class="header-box">
                                <div class="title">{{ item.title }}</div>
                                <div class="btn" v-if="isAdmin">
                                    <van-button size="mini" type="danger" @click="handleDeleteNotice(item)">删除</van-button>
                                </div>
                            </div>

                            <!-- 内容区域开始 -->
                            <div class="content-box">
                                <div class="text-panel">{{ item.contents }}</div>
                                <div class="image-panel" v-if="item.image_url">
                                    <div class="image-item" v-for="(value, index) in item.image_url.split(',')" :key="index">
                                        <van-image
                                            width="80"
                                            height="80"
                                            fit="contain"
                                            :src="global.MINIO_FILE_DOMAIN + value"
                                            @click="handleImagePreview(global.MINIO_FILE_DOMAIN + value)"
                                        />
                                    </div>
                                </div>
                            </div>

                            <!-- 尾部区域开始 -->
                            <div class="footer-box">{{ item.create_time }}</div>
                        </div>
                    </template>
                    <template v-else>
                        <TridentEmpty v-if="!loading" message="暂无公告"/>
                    </template>

                    <!-- 返回顶部 -->
                    <van-back-top><i class="iconfont icon-top" style="font-size: 30px;"></i></van-back-top>
                </van-list>
            </van-pull-refresh>
        </div>
        <!-- 列表区域结束 -->

        <!-- 添加标签弹层区域开始 -->
        <van-popup
            v-model:show="showPopup"
            position="top"
            closeable
            round
            :style="{ height: '58%' }"
        >
            <div class="popup-wrap">
                <div class="title-box">发布公告</div>
                <van-form @submit="onSubmit">
                    <van-cell-group inset>
                        <!-- 标题 -->
                        <van-field
                            v-model="publishGroupNoticeParams.title"
                            label="标题"
                            name="title"
                            required
                            clearable
                            placeholder="请输入标题"
                            :rules="[{ required: true, message: '请输入标题' }]"
                        />

                        <!-- 图片 -->
                        <van-field name="uploader" label="图片">
                            <template #input>
                                <van-uploader
                                    v-model="uploaderList"
                                    :after-read="handleAfterRead"
                                    :max-count="3"
                                    @delete="handleDelete"
                                />
                            </template>
                        </van-field>


                        <!-- 内容 -->
                        <van-field
                            v-model="publishGroupNoticeParams.contents"
                            rows="2"
                            autosize
                            label="内容"
                            type="textarea"
                            clearable
                            maxlength="50"
                            placeholder="请输入内容"
                            show-word-limit
                        />

                        <!-- 备注 -->
                        <van-field
                            v-model="publishGroupNoticeParams.note"
                            clearable
                            label="备注"
                            placeholder="请输入备注"
                        />
                    </van-cell-group>

                    <div class="btn-box">
                        <van-button
                            block
                            native-type="submit"
                            round
                            color="#27BA9B"
                            type="primary"
                            size="normal"
                        >发 布</van-button>
                    </div>
                </van-form>
            </div>
        </van-popup>
        <!-- 添加标签弹层区域结束 -->

    </div>
</template>

<script lang="ts" setup>
import { reqGroupChatDetailAPI } from '@/apis/groupChat'
import { reqDeleteGroupNoticeAPI, reqGroupNoticeListAPI, reqPublishGroupNoticeAPI } from '@/apis/groupNotice'
import { reqUploadImageAPI } from '@/apis/uploadFile'
import { useUserStore } from '@/store/modules/user'
import type { Member } from '@/types/groupChat'
import type { GroupNotice, GroupNoticeListParams, PublishGroupNoticeParams } from '@/types/groupNotice'
import { removeLastComma } from '@/utils/tools'
import dayjs from 'dayjs'
import { showConfirmDialog, showImagePreview, showSuccessToast, showToast } from 'vant'
import { inject, onMounted, reactive, ref } from 'vue'
import { useRoute } from 'vue-router'

// ----------------- 定义全局变量开始 -----------------
// 全局属性
const global: any = inject('global')

// 骨架屏
const isSkeleton = ref<boolean>(false)

// 路由
const route = useRoute()

// 用户存储
const userStore = useUserStore()
// ----------------- 定义全局变量结束 -----------------



onMounted(async() => {
    await getGroupChatInfo()
})



// ----------------- 获取群聊信息开始 -----------------
// 是否管理员
const isAdmin = ref<boolean>(false)

// 获取群聊信息
const getGroupChatInfo = async () => {
    const result = await reqGroupChatDetailAPI(route.query.gid as never)
    result.data.member.forEach((item: Member) => {
        if (item.is_admin == 1 && item.uid == userStore.profile.user.uid) {
            isAdmin.value = true
        }
    })
}
// ----------------- 获取群聊信息结束 -----------------



// ----------------- 下拉刷新功能开始 -----------------
const refreshing = ref<boolean>(false)
const onRefresh = async () => {
    // 清空列表数据
    finished.value = false

    // 将 loading 设置为 true，表示处于加载状态
    loading.value = true

    groupNoticeListParams.page = 1

    await getGroupNoticeList()
}
// ----------------- 下拉刷新功能结束 -----------------



// --------------- 处理公告列表功能开始 ---------------
// 加载中
const loading = ref(false)

// 完成
const finished = ref(false)

// 公告列表参数
const groupNoticeListParams = reactive<GroupNoticeListParams>({
    gid: route.query.gid as never,
    page: 1,
})

// 公告列表
const groupNoticeList = ref<GroupNotice[]>([])

// 总条数
const total = ref<number>(0)

// 总页数
const totalPage = ref<number>(0)

// 获取消息列表
const getGroupNoticeList = async () => {
    isSkeleton.value = true
    if (refreshing.value) {
        groupNoticeList.value = []
        refreshing.value = false
    }

    loading.value = true

    const result = await reqGroupNoticeListAPI(groupNoticeListParams)
    groupNoticeList.value.push(...result.data.group_notices)
    total.value = result.data.total
    totalPage.value = result.data.total_page
    
    if (groupNoticeListParams.page < result.data.total_page) {
        groupNoticeListParams.page++
    } else {
        finished.value = true
    }

    loading.value = false
    isSkeleton.value = false
}
// ---------------- 处理消息列表功能结束 ----------------



// ------------------ 处理图片预览开始 ------------------
const handleImagePreview = (image_url: string) => {
    showImagePreview({images: [image_url], closeable: true})
}
// ------------------ 处理图片预览结束 ------------------



// ------------------ 处理发布公告开始 ------------------
const showPopup = ref<boolean>(false)

// 上传图片列表
const uploaderList = ref([])

// 临时图片列表
const tempImageList:any = ref([])

// 发布公告参数
const publishGroupNoticeParams = ref<PublishGroupNoticeParams>({
    gid: route.query.gid as never,
    title: '',
    contents: '',
    image_url: '',
    note: ''
})

// 显示发布公告弹层
const handleShowPublish = () => {
    publishGroupNoticeParams.value.title = ''
    publishGroupNoticeParams.value.contents = ''
    publishGroupNoticeParams.value.image_url = ''
    publishGroupNoticeParams.value.note = ''
    tempImageList.value = []
    uploaderList.value = []
    showPopup.value = true
}

// 发布
const onSubmit = async () => {
    let image_url = ''
    tempImageList.value.forEach((item: any) => {
        image_url += item.image_url + ','
    })
    // 去除最后一个逗号
    publishGroupNoticeParams.value.image_url = removeLastComma(image_url)
    
    await reqPublishGroupNoticeAPI(publishGroupNoticeParams.value)
    showSuccessToast('发布成功')
    showPopup.value = false
    groupNoticeList.value.unshift({
        id: 0,
        gid: publishGroupNoticeParams.value.gid,
        title: publishGroupNoticeParams.value.title,
        contents: publishGroupNoticeParams.value.contents,
        image_url: publishGroupNoticeParams.value.image_url,
        note: publishGroupNoticeParams.value.note + '' ,
        status: 1,
        create_time: dayjs().format('YYYY-MM-DD HH:mm:ss'),
        update_time: ''
    })
}
// ----------------- 处理发布公告结束 -----------------



// ----------------- 处理图片上传开始 -----------------
const handleAfterRead = async (file: any) => {
    // 图片类型限制
	const imageTypes = [
		'image/jpg',
		'image/jpeg',
		'image/png',
	]
	if (!imageTypes.includes(file.file.type)) {
		showToast('图片类型要求：jpeg、jpg、png')
		return false
	}

	// 图片大小限制 2M
	if (file.size > 1024 * 1024 * 2) {
		showToast('图片大小不能超过2M')
		return false
	}


    file.status = 'uploading'
    file.message = '上传中...'

    const formData = new FormData()
    // 必须要第三个参数，名称随便
    formData.append("image", file.file, 'xxx.jpg')
    formData.append("image_path", 'easychat/groupchat_notice')
    // 请求上传图片接口
    const {data:result} = await reqUploadImageAPI(formData)
    if (result.status_code != 200) {
        showToast(result.message)
        return false
    }

    if (result.status_code != 200) {
        showToast('发送图片失败')
        return false
    }

    file.status = 'done'
    file.message = '上传完成'
    
    // 追加图片
    tempImageList.value.push({file_name: file.file.name, image_url: result.data.relative_url})
}
// ----------------- 处理图片上传结束 -----------------



// ----------------- 处理删除图片开始 -----------------
const handleDelete = (file: any) => {
    const index = tempImageList.value.findIndex((item:any) => item.name == file.file.name)
    tempImageList.value.splice(index, 1)
}
// ----------------- 处理删除图片结束 -----------------



// ----------------- 处理删除公告开始 -----------------
const handleDeleteNotice = (item: GroupNotice) => {
    if (!isAdmin.value) {
        showToast('管理员才能删除公告')
        return false
    }
    showConfirmDialog({
        message: '确定要删除公告吗?',
        confirmButtonColor: '#27BA9B'
    })
    .then(async() => {
        await reqDeleteGroupNoticeAPI(item.id + '');

        // 删除
        const index = groupNoticeList.value.findIndex(value => value.id == item.id)
        groupNoticeList.value.splice(index, 1)
        
        showSuccessToast('删除公告成功')
    })
    .catch(() => {
        // on cancel
    })
}
// ----------------- 处理删除公告结束 -----------------
</script>

<style scoped lang="scss">
page,
.container {
    height: 100%;
    // 列表区域开始
    .content-wrap {
        padding-top: 50px;
        .list-wrap {
            padding: 0 10px;
            margin-bottom: 10px;
            .item {
                background-color: #fff;
                padding: 15px;
                border-radius: 10px;
                margin-top: 5px;

                // 头部区域开始
                .header-box {
                    font-size: 16px;
                    display: flex;
                    justify-content: space-between;
                    align-items: center;
                }

                // 内容区域开始
                .content-box {
                    margin: 10px 0px;
                    border-top: 1px solid #e7e7e7;
                    border-bottom: 1px solid #e7e7e7;
                    padding: 10px 0px;
                    .text-panel {
                        font-size: 14px;
                        line-height: 18px;
                    }
                    .image-panel {
                        display: flex;
                        flex-wrap: wrap;
                        .image-item {
                            width: 85px;
                            height: 85px;
                            display: flex;
                            align-items: center;
                            justify-content: center;
                            border: 1px solid #e7e7e7;
                            margin-right: 8px;
                            border-radius: 5px;
                            margin-top: 10px;
                            &:nth-child(4n) {
                                margin-right: 0px;
                            }
                        }
                    }
                }

                // 尾部区域开始
                .footer-box {
                    display: flex;
                    justify-content: flex-end;
                    color: #d3d2d2;
                    font-size: 12px;
                }
            }

            // 骨架屏区域开始
            .skeleton-item {
                background-color: #fff;
                border-radius: 10px;
                margin-top: 5px;
                .skeleton-box {
                    padding: 15px;
                    width: 100%;
                    .title {
                        display: flex;
                        align-items: center;
                        padding-bottom: 6px;
                    }

                    .content {
                        border-top: 1px solid #f1f1f1;
                        padding-top: 10px;
                    }
                    .footer {
                        padding-top: 10px;
                        display: flex;
                        justify-content: flex-end;
                    }
                }
            }
        }
    }

    // 添加标签弹层区域开始
    .popup-wrap {
        .title-box {
            margin-top: 20px;
            text-align: center;
            font-size: 18px;
            font-weight: bold;
            margin-bottom: 10px
        }

        .btn-box {
            display: flex;
            justify-content: center;
            margin: 15px;
        }
    }
}
</style>